<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!--
Design by Free CSS Templates
http://www.freecsstemplates.org
Released for free under a Creative Commons Attribution 2.5 License

Name       : Temperate 
Description: A two-column, fixed-width design with dark color scheme.
Version    : 1.0
Released   : 20121205

-->
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="keywords" content="" />
<meta name="description" content="" />
<!-- <meta http-equiv="refresh" content="30;url=index.html" /> -->
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>My OmniTrack</title>
<link href='http://fonts.googleapis.com/css?family=Oswald:400,300' rel='stylesheet' type='text/css' />
<link href='http://fonts.googleapis.com/css?family=Abel|Satisfy' rel='stylesheet' type='text/css' />
<link href="css/default.css" rel="stylesheet" type="text/css" media="all" />
 <link rel="stylesheet" href="css/nivo-slider.css" type="text/css" media="screen" />
    <link rel="stylesheet" href="css/slidestyle.css" type="text/css" media="screen" />
 <link rel="stylesheet" href="css/themes/default/default.css" type="text/css" media="screen" />
 <link href="css/iphone.css" media="mobile" rel="stylesheet" type="text/css" />
<!--[if IE 6]>
<link href="default_ie6.css" rel="stylesheet" type="text/css" />
<![endif]-->
<!-- For google map api and style -->
<script
	src="http://maps.googleapis.com/maps/api/js?key=AIzaSyAhM2wI3jzOrKjEl0akPPBb84wp4xrPQ40"
	type="text/javascript"></script>
	<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
	<script
	src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
	<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerwithlabel/1.1.5/src/markerwithlabel_packed.js"></script>
   <!--  <script type='text/JavaScript' src='http://www.onemap.sg/API/JS/?accessKEY=qLKYNUtRzHQupRKu5yD5EQokuQj1MhBz6Xq4GIOkLYvLYHnIf8N0cS6OSee38QsIr+AwyyKlQKcqXOxzdNmuQdAMaDcBcPBAsggQ8UxtT5swELJbwpKPOOOcpFo9Ls0FWL3DpdRgbE0=|mv73ZvjFcSo=&v=2.8&type=full'></script> -->

<style>

#Geofence,#GeofencePanel
{
padding:0px;
border:solid 1px #c3c3c3;
}
#Geofence
{
width:278px;
background-color:#0172B6;
padding:10px 0px 0px 20px;
}
#ClearGeofence
{
width:279px;
height:40px;
background-color:#0172B6;
padding:10px 0px 0px 20px;
display:none;
}
#Location
{
width:278px;
background-color:#0172B6;
padding:10px 0px 0px 20px;
}
#GeofencePanel
{
padding:10px;
width:277px;
display:none;
}
#ClearGeofencePanel
{
padding:0px;
border:solid 1px #c3c3c3;
padding:10px;
width:277px;
visibility:hidden;
display:none;
}
#ViewImg,#CreateImg,#imgAlert,#Geofence,#ClearGeofence,#ClearImg,#ClearAlertImg
  {
    cursor:pointer;
  }  

.gmap3{
margin: 0px auto;
/* border: 1px dashed #C0C0C0; */
	width: 800px;
	height: 600px;
	border-style:double;
border-width:medium;
}
.rpanel{
margin: 0px auto;
width:300px;
height:1000px;
background-image:url("images/SidebarPanel.jpg");
background-repeat:no-repeat;
}
.rNoAlert{
margin: 0px auto;
background-image:url("images/NoAlert.jpg");
background-repeat:no-repeat;
width:240px;
height:80px;
margin-top: 4;
margin-left:230px;
}
.rAlert{
margin: 0px auto;
background-image:url("images/Alert.jpg");
background-repeat:no-repeat;
width:240px;
height:80px;
margin-top: 4;
margin-left:230px;
}
#info{
color:black;
font-size: 16px;
padding: 10px 0px 0px 10px;
width:270px;
}
#location{
font-weight:bold;
}
.labels {
     color: white;
     background-color: #0172b6;
     font-family: "Lucida Grande", "Arial", sans-serif;
     font-size: 12px;
     font-weight: bold;
     text-align: center;
     width: 25px;
     border: 1px solid black;
     white-space: nowrap;
   }
   .fencelabels {
     color: white;
     background-color: #0172b6;
     font-family: "Lucida Grande", "Arial", sans-serif;
     font-size: 12px;
     font-weight: bold;
     text-align: center;
     width: 50px;
     border: 1px solid black;
     white-space: nowrap;
   }
   
    span.title {
   
   color: #3091F2;
   
   }
   

#desc {
 float: left;
 margin: 0 25px 10px 20px;
 width: 10em;
}

#markers {
 position:absolute;
  margin: 800px auto;
 width:200px;
 height:110px;
}

.drag {
 position: absolute;
 width: 32px;
 height: 32px;
}


 #desc {
  margin: 100px 14px 0;
  width: 93%;
 }
 .include >b {
  float: right;
  margin-top: 17px;
 }

 #markers {
	/* center horizontal and do not overlap the map */
  position: absolute;
  margin: 800px auto;
	width: 10em;
	height: 6em;
	margin-top: 0em;
	margin-left:15em;
 }

 #markers > p {
  margin-top: 0;
  font-size: 80%;
 }
 
    .style1
    {
        width: 1165px;
        margin-left:70px;
    }
    
    .style2
    {
        height: 48px;
        font-size: 22px;
        width: 295px;
    }
    .style3
    {
        height: 48px;
        font-size: 30px;
    }
    .style4
    {
        height: 48px;
        font-size: 18px;
    }

    #frontlayer {
        position: absolute;
        top: 267px;
        margin: 0px auto;
        padding : 30px;
        width: 740px;
        height: 500px;
        background-color: #ffffff;
        display:none;
        border: 1px solid black;
        z-index: 1;
    }

</style>

<script type="text/javascript">
    if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPad/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/android/gi)) || (navigator.userAgent.match(/Windows Phone/i))) { location.replace("phonemap.html"); }

</script>
<script type="text/javascript">	
    var map, iw, drag_area, actual, obj;
    var dummy, z_index = 0;
    var checkInputMarker = 0;
    var div;
    var lat = "";
    var lng = "";
    var geofencelat;
    var geofencelng;
    var geofenceDistance;
    var datalat = [];
    var datalng = [];
    var dataDate = [];
    var movedOutGeofenceCount = 0;
    var address;
    var dateTime;
    var markerHist = [];
    var markerTemp = [];
    var markerPerm = [];
    
    function displayMap() {
        //create map
        var mapOptions = {
            zoom: 12,
            center: new google.maps.LatLng(1.31, 103.8),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        map = new google.maps.Map(document.getElementById("map"), mapOptions);    	
    }
    
    function initialize() {
    	$(document).ready(function(){
  		  $("#Geofence").click(function(){
  			    $("#GeofencePanel").slideToggle("slow");    
  			  $("#ClearGeofence").slideToggle("slow");
		    $("#ClearGeofencePanel").slideToggle("slow");
  			document.getElementById('ClearGeofencePanel').style.visibility = 'hidden';
  		  });
  		  $("#ClearGeofence").click(function(){
  			document.getElementById('ClearGeofencePanel').style.visibility = 'visible';
			    $("#ClearGeofencePanel").slideToggle("slow");
		  });
    	});
	
    	displayMap();
    	
        $.getJSON('./getOutsidegeofence', function (data) {
        	var no = 1;
        	var htmlString = "<table border='0' width='100%' cellspacing ='3' cellpadding='8'><tr><td bgcolor='#FA5858' colspan='7' style='color: #000000' class='style5'><b style='color: #000000; font-size: 18px'>&nbsp;&nbsp;Outside Geofence Details (First 5 Locations)</b></td></tr><tr><td bgcolor='#87B2F9' style='color: #000000'><center><b>No.</b></center></td><td bgcolor='#87B2F9' style='color: #000000'><center><b>Date & Time</b></center></td><td bgcolor='#87B2F9' style='color: #000000'><center><b>Geofence Name</b></center></td><td bgcolor='#87B2F9' style='color: #000000'><center><b>Latitude</b></center></td><td bgcolor='#87B2F9' style='color: #000000'><center><b>Longitude</b></center></td></tr>";
            $.each(data.aaData, function (i, id) {
            	if(no == 1){
            	document.getElementById("imgNoAlert").className = "rAlert";
            	document.getElementById('imgNoAlert').id = 'imgAlert';
            	$(document).ready(function(){
            		  $("#imgAlert").click(function(){		    
            			    $("#frontlayer").slideToggle("slow");
            			  });
            		});
            	}
            	if(no < 6){
            	htmlString = htmlString + "<tr><td bgcolor='#87B2F9' style='color: #000000; padding: 15px;'><center>" + no + "</center></td>";
            	htmlString = htmlString + "<td bgcolor='#87B2F9' style='color: #000000; padding: 15px;'><center>" + id.DateTime + "</center></td>";
            	htmlString = htmlString + "<td bgcolor='#87B2F9' style='color: #000000; padding: 15px;'><center>" + id.GeofenceName + "</center></td>";
            	htmlString = htmlString + "<td bgcolor='#87B2F9' style='color: #000000; padding: 15px;'><center>" + id.latitude + "</center></td>";
            	htmlString = htmlString + "<td bgcolor='#87B2F9' style='color: #000000; padding: 15px;'><center>" + id.longitude + "</center></td>";
            	no++;
            	}
            });
            htmlString = htmlString + "</table><p>&nbsp;</p>";
            htmlString = htmlString + "<p><img id='ClearAlertImg' alt='Clear all alerts' src='images/ClearAlertButton.png' height='30' width='144' onClick='clearAlerts()'/></p>";
            $("#frontlayer").html(htmlString);
 
        });

                
        geocoder = new google.maps.Geocoder();
        //get json starts here
        $.getJSON('./data?type=1', function (data) {
            var hlbl = 1;
            $.each(data.aaData, function (i, id) {
                //adding markers start here
                var latLng = new google.maps.LatLng(id.lat, id.lng);

                //show info window
                //create map
                var mapOptions = {
                    zoom: 12,
                    center: new google.maps.LatLng(id.lat, id.lng),
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                }
                map = new google.maps.Map(document.getElementById("map"), mapOptions);

                //end map
                dateTime = id.dateTime;
                
                var lat = id.lat;
                var lng = id.lng;
                coordinate = lat + "," + lng;
                var inXYList = lng + "," + lat;
                var inputSR, outputSR;
                inputSR = 4326;
                outputSR = 3414;
/*                 var CoordConvertorObj = new CoordConvertor();
                CoordConvertorObj.ConvertCoordinate(inXYList, inputSR, outputSR, reverseGeocodeVal); */
                
                
                geocoder.geocode({ 'latLng': latLng }, function (results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        if (results[1]) {
                            var a = google.maps;
                            //map = new google.maps.Map(document.getElementById("map"), mapOptions);
                            iw = new a.InfoWindow();
                            a.event.addListener(map, "click", function () { if (iw) iw.close() });
                            drag_area = document.getElementById("markers");
                            var c = drag_area.getElementsByTagName("div");
                            for (var f = 0; f < c.length; f++) {
                                var d = c[f];
                                d.onmousedown = d.ontouchstart = initDrag
                            } dummy = new DummyOView();
                        } else {
                            /* google.maps.event.addListener(marker, 'click', function() {
                            content : id.lat + "," +id.lng+ " <br> " + id.dateTime
                            });	 */
                            $("#info").html("<div id ='info'><p>Latitude: <span class='title'>" + parseFloat((id.lat).toFixed(3)) + ",</span>Longitude: <span class='title'>" + parseFloat((id.lng).toFixed(3)) + "</span></p><p>Date & Time : <br/><span class='title'>" + id.dateTime + "</span></p><p><input type='checkbox' id='His' onchange='showHistory()' value='Show History' />Show History</p></div>");
                        }
                    } else {
                        /* google.maps.event.addListener(marker, 'click', function() {
                        content : id.lat + ", " +id.lng + " <br> " + id.dateTime
                        });	 */
                        $("#info").html("<div id ='info'><p>Latitude: <span class='title'>" + parseFloat((id.lat).toFixed(3)) + ",</span>Longitude: <span class='title'>" + parseFloat((id.lng).toFixed(3)) + "</span></p><p>Date & Time : <br/><span class='title'>" + id.dateTime + "</span></p><p><input type='checkbox' id='His' onchange='showHistory()' value='Show History' />Show History</p></div>");
                    }
                });
                 var marker = new MarkerWithLabel({
                    map: map,
                    position: latLng,
                    icon: "../images/bluemarker5.png",
                    labelContent: hlbl,
                    labelAnchor: new google.maps.Point(12, 55),
                    labelClass: "labels"
                }); 
                //get json ends here      

            });

        });
    }
    
    // end of initialize
    
    function reverseGeocodeVal(outXY) {

        var oneMapAddressInfoObj = new GetAddressInfo;
        oneMapAddressInfoObj.XY = outXY;

        oneMapAddressInfoObj.GetAddress(function (addressData) {
            DisplayData(addressData);
        });
    }

   /*  function DisplayData(addressData) {
        if (addressData.results == "No results") {
            //alert("No results");
        }
        else {
            if (addressData.results[0].BUILDINGNAME == null && addressData.results[0].ROAD == null && addressData.results[0].POSTALCODE == null) {
                //alert("Could not identify the place");
            }
            else {

            	if (addressData.results[0].BUILDINGNAME != null && addressData.results[0].ROAD != null && addressData.results[0].POSTALCODE != null) {

                        address = addressData.results[0].BUILDINGNAME + " - " + addressData.results[0].ROAD + " " + addressData.results[0].POSTALCODE;
                        //alert(address);
                }

                if (addressData.results[0].BUILDINGNAME == null && addressData.results[0].ROAD != null && addressData.results[0].POSTALCODE != null) {

                        address = addressData.results[0].ROAD + " " + addressData.results[0].POSTALCODE;
                        //alert(address);
                }

                if (addressData.results[0].BUILDINGNAME == null && addressData.results[0].ROAD == null && addressData.results[0].POSTALCODE != null) {

                        address = addressData.results[0].POSTALCODE;
                        //alert(address);
                }

                if (addressData.results[0].BUILDINGNAME == null && addressData.results[0].ROAD != null && addressData.results[0].POSTALCODE == null) {

                        address = addressData.results[0].ROAD;
                        //alert(address);
                }
                $("#info").html("<div id ='info'><p>Address : <br/><span class='title'>" + address + "</span></p><p>Date & Time :<br/><span class='title'>" + dateTime + "</span></p><p><input type='checkbox' name='His' id='His' onchange='showHistory()' value='Show History' />  Show History</p><p><input type='checkbox' name='cbShowPermanentGeoFence' id='cbShowPermanentGeoFence' onchange='showPermanentGeofence()' value='Show Permanent GeoFence'/>  Show Permanent GeoFence</p><p><input type='checkbox' name='cbShowTemporaryGeoFence' id='cbShowTemporaryGeoFence' onchange='showTemporaryGeofence()' value='Show Temporary GeoFence'/>  Show Temporary GeoFence</p><p>&nbsp;</p></div>");

            }
        }

    }
 */

    function showHistory() {

        if (document.getElementById("His").checked == true) {

            geocoder = new google.maps.Geocoder();

            //get json starts here
            $.getJSON('./data?type=10', function (data) {
                var hlbl = 1;
                $.each(data.aaData, function (i, id) {
                    //adding markers start here
                    var latLng = new google.maps.LatLng(id.lat, id.lng);

                    var marker = new MarkerWithLabel({
                        map: map,
                        position: latLng,
                        icon: "../images/tealmarker1.png",
                        labelContent: hlbl++,
                        labelAnchor: new google.maps.Point(12, 55),
                        labelClass: "labels"
                    });
                    //adding markers ends here
					markerHist.push(marker);
                    //show info window

                    geocoder.geocode({ 'latLng': latLng }, function (results, status) {
                        if (status == google.maps.GeocoderStatus.OK) {
                            if (results[1]) {
                                /* marker.info = new google.maps.InfoWindow({
						
                                }); */
                                google.maps.event.addListener(marker, 'click', function () {
                                    $("#info").html("<div id ='info'><p>Address :<br/><span class='title'>" + results[1].formatted_address + "</span></p><p>Date & Time :<br/><span class='title'>" + id.dateTime + "</span></p><p><input type='checkbox' id='His' onchange='showHistory()' value='Show History' />Show History</p>");
                                });

                            } else {
                                google.maps.event.addListener(marker, 'click', function () {
                                    $("#info").html("<div id ='info'><p>Latitude: <span class='title'>" + parseFloat((id.lat).toFixed(3)) + ",</span>Longitude: <span class='title'>" + parseFloat((id.lng).toFixed(3)) + "</span></p><p>Date & Time :<br/><span class='title'>" + id.dateTime + "</span></p><p><input type='checkbox' id='His' onchange='showHistory()' value='Show History' checked='check' />Show History</p></div>");
                                });

                            }
                        } else {
                            google.maps.event.addListener(marker, 'click', function () {
                                $("#info").html("<div id ='info'><p>Latitude: <span class='title'>" + parseFloat((id.lat).toFixed(3)) + ",</span>Longitude: <span class='title'>" + parseFloat((id.lng).toFixed(3)) + "</span></p><p>Date & Time : <br/><span class='title'>" + id.dateTime + "</span></p><p><input type='checkbox' id='His' onchange='showHistory()' value='Show History' checked='check'/>Show History</p></div>");
                            });

                        }
                    });

                });

            });
            //get json ends here 
        }
        else if (document.getElementById("His").checked == false) {
        	clearOverlaysHist();
        }
    }
    
    function showPermanentGeofence() {

        if (document.getElementById("cbshowPermFence").checked == true) {
        	
            geocoder = new google.maps.Geocoder();

            //get json starts here
            $.getJSON('./getgeofence?fenceType=Permanent', function (data) {
                var hlbl = 1;
                $.each(data.aaData, function (i, id) {
                    //adding markers start here
                    var latLng = new google.maps.LatLng(1.3667, 103.80);
                    var options = {
                        'zoom': 12,
                        'center': latLng,
                        'mapTypeId': google.maps.MapTypeId.ROADMAP
                    };

                    var hlbl = "P";
                    var marker = new MarkerWithLabel({
                        map: map,
                        position: new google.maps.LatLng(id.latitude, id.longitude),
                        icon: "../images/GeoFenceMarker.png",
                        labelContent: hlbl,
                        labelAnchor: new google.maps.Point(12, 45),
                        labelClass: "labels"
                    });
                    markerPerm.push(marker);
                    // Add a Circle overlay to the map.          
               var circle = new google.maps.Circle({
                        map: map,
                        radius: parseFloat(id.distance), // 3000 km
                        fillOpacity: 0.4,
                        strokeWeight:1.5,
                        strokeColor: "#FF0000",
                        fillColor: "#FF0000"
                    });
               markerPerm.push(circle);
               google.maps.event.addListener(marker, 'click', function () {
               	$("#latitude").html("<p>Latitude : " + id.latitude + "</p>");
               	$("#longitude").html("<p>Longitude : " + id.longitude + "</p>");
               	});
               circle.bindTo('center', marker, 'position');
           });

       });
       //get json ends here 
   }
        else if (document.getElementById("cbshowPermFence").checked == false) {
        	clearPermGeo();
        }
    }
    
    function showTemporaryGeofence() {

        if (document.getElementById("cbshowTempFence").checked == true) {

            geocoder = new google.maps.Geocoder();

            //get json starts here
            $.getJSON('./getgeofence?fenceType=Temporary', function (data) {
                var hlbl = 1;
                $.each(data.aaData, function (i, id) {
                    //adding markers start here
                    var latLng = new google.maps.LatLng(1.3667, 103.80);
                    var options = {
                        'zoom': 12,
                        'center': latLng,
                        'mapTypeId': google.maps.MapTypeId.ROADMAP
                    };
                    
                    var hlbl = "T";
                    var marker = new MarkerWithLabel({
                        map: map,
                        position: new google.maps.LatLng(id.latitude, id.longitude),
                        icon: "../images/GeoFenceMarker.png",
                        labelContent: hlbl,
                        labelAnchor: new google.maps.Point(12, 45),
                        labelClass: "labels"
                    });
                    markerTemp.push(marker);
                    // Add a Circle overlay to the map.          
                    var circle = new google.maps.Circle({
                        map: map,
                        radius: parseFloat(id.distance), // 3000 km
                        fillOpacity: 0.4,
                        strokeWeight:1.5,
                        strokeColor: "#00FF0C",
                        fillColor: "#00FF0C"
                    });
                    markerTemp.push(circle);
                    google.maps.event.addListener(marker, 'click', function () {
                    	$("#latitude").html("<p>Latitude : " + id.latitude + "</p>");
                    	$("#longitude").html("<p>Longitude : " + id.longitude + "</p>");
                    	});
                    circle.bindTo('center', marker, 'position');
                });

            });
            //get json ends here 
        }
        else if (document.getElementById("cbshowTempFence").checked == false) {
        	clearTempGeo();
        }
    }
    
    function PermanentGeofence(){
    	if (document.getElementById("cbPermanentFence").checked == true) {
    		document.getElementById("cbPermanentFence").checked = true;
    		document.getElementById("cbTemporaryFence").checked = false;
    	}
    	if (document.getElementById("cbPermanentFence").checked == false) {
    		document.getElementById("cbPermanentFence").checked = true;
    		document.getElementById("cbTemporaryFence").checked = false;
    	}

    }
    
    function TemporaryGeofence(){
    	if (document.getElementById("cbTemporaryFence").checked == true) {
    		document.getElementById("cbPermanentFence").checked = false;
    		document.getElementById("cbTemporaryFence").checked = true;
    	}
    	if (document.getElementById("cbTemporaryFence").checked == false) {
    		document.getElementById("cbPermanentFence").checked = false;
    		document.getElementById("cbTemporaryFence").checked = true;
    	}

    }
    
    function ClearPermanentGeofence(){
    	if (document.getElementById("cbClearPermanentFence").checked == true) {
    		document.getElementById("cbClearPermanentFence").checked = true;
    		document.getElementById("cbClearTemporaryFence").checked = false;
    	}
    	if (document.getElementById("cbClearPermanentFence").checked == false) {
    		document.getElementById("cbClearPermanentFence").checked = true;
    		document.getElementById("cbClearTemporaryFence").checked = false;
    	}
    }
    
    function ClearTemporaryGeofence(){
    	if (document.getElementById("cbClearTemporaryFence").checked == true) {
    		document.getElementById("cbClearPermanentFence").checked = false;
    		document.getElementById("cbClearTemporaryFence").checked = true;
    	}
    	if (document.getElementById("cbClearTemporaryFence").checked == false) {
    		document.getElementById("cbClearPermanentFence").checked = false;
    		document.getElementById("cbClearTemporaryFence").checked = true;
    	}
    }

    function DummyOView() {
        this.setMap(map);
        this.draw = function () { }
    } DummyOView.prototype = new google.maps.OverlayView();
    function fillMarker(a) {
        if (checkInputMarker = 0) {
            var b = document.createElement("div");
            b.style.backgroundImage = "url(" + a + ")";
            var c; if (obj.id == "m1") { c = "0px" }
            else
                if (obj.id == "m2") {
                    c = "50px"
                }
                else
                    if (obj.id == "m3") {
                        c = "100px"
                    }
            b.style.left = c;
            b.id = obj.id;
            b.className = "drag";
            b.onmousedown = b.ontouchstart = initDrag;
            drag_area.replaceChild(b, obj);
            obj = null
        } else {
            var b = document.createElement("div");
            b.style.backgroundImage = "url(" + a + ")";
            var c; if (obj.id == "m1") { c = "0px" }
            else
                if (obj.id == "m2") {
                    c = "50px"
                }
                else
                    if (obj.id == "m3") {
                        c = "100px"
                    }
            b.style.left = c;
            b.id = obj.id;
            b.className = "drag";
            b.onmousedown = b.ontouchstart = initDrag;
            drag_area.replaceChild(b, obj);
            obj = null
        }
    }
    function highestOrder() {
        return z_index
    }
    function createDraggedMarker(c, f) {
        var d = google.maps;
        var h = {
            url: f,
            size: new d.Size(32, 32),
            anchor: new d.Point(15, 32)
        };
        var i = { url: "http://maps.gstatic.com/mapfiles/kml/paddle/A_maps.shadow.png",
            size: new d.Size(59, 32),
            anchor: new d.Point(15, 32)
        };
        var g = new d.Marker({
            position: c,
            map: map,
            clickable: true,
            draggable: true,
            optimized: false,
            raiseOnDrag: false,
            icon: h,
            shadow: i,
            zIndex: highestOrder()
        });

        d.event.addListener(g, "click", function () {
            actual = g;
            var a = actual.getPosition().lat();
            var b = actual.getPosition().lng();
            iw.setContent(a.toFixed(6) + ", " + b.toFixed(6));
            iw.open(map, this);
            lat = g.getPosition().lat().toFixed(6);
            lng = g.getPosition().lng().toFixed(6);
            document.getElementById('latitude').innerHTML = "<p>Latitude : " + lat + "</p>";
            document.getElementById('longitude').innerHTML = "<p>Longitude : " + lng + "</p>";
        });
        d.event.addListener(g, "dragstart", function () {
            if (actual == g)
                iw.close();
            z_index += 1;
            g.setZIndex(highestOrder());
            
            
            
        });
        d.event.addListener(g, "dragend", function () {
            lat = g.getPosition().lat().toFixed(6);
            lng = g.getPosition().lng().toFixed(6);
            document.getElementById('latitude').innerHTML = "<p>Latitude : " + lat + "</p>";
            document.getElementById('longitude').innerHTML = "<p>Longitude : " + lng + "</p>";
            
            
            
        });
        lat = g.getPosition().lat().toFixed(6);
        lng = g.getPosition().lng().toFixed(6);
        document.getElementById('latitude').innerHTML = "<p>Latitude : " + lat + "</p>";
        document.getElementById('longitude').innerHTML = "<p>Longitude : " + lng + "</p>";
        
        if (parseFloat(document.getElementById("tbFenceDistance").value) <= 1000 && lat != "") {
            var latLng = new google.maps.LatLng(1.3667, 103.80);
            var options = {
                'zoom': 12,
                'center': latLng,
                'mapTypeId': google.maps.MapTypeId.ROADMAP
            };
            map = new google.maps.Map(document.getElementById('map'), options);
            // Create a draggable marker which will later on be binded to a          
            // Circle overlay.          
            var marker = new google.maps.Marker({
                map: map,
                position: new google.maps.LatLng(lat, lng),
                draggable: true,
                title: 'Drag me!'
            });
            // Add a Circle overlay to the map.  
            var circle = new google.maps.Circle({
                    map: map,
                    radius: parseFloat(document.getElementById("tbFenceDistance").value), // 3000 km
                    fillOpacity: 0.4,
                    strokeWeight:1.5,
                    strokeColor: "#FF0000",
                    fillColor: "#FF0000"
                });
            if(document.getElementById("cbTemporaryFence").checked == true){
                var circle = new google.maps.Circle({
                    map: map,
                    radius: parseFloat(document.getElementById("tbFenceDistance").value), // 3000 km
                    fillOpacity: 0.4,
                    strokeWeight:1.5,
                    strokeColor: "#00FF0C",
                    fillColor: "#00FF0C"
                    });
            }
            google.maps.event.addListener(marker, "dragend", function () {
                lat = marker.getPosition().lat().toFixed(6);
                lng = marker.getPosition().lng().toFixed(6);
                document.getElementById('latitude').innerHTML = "<p>Latitude : " + lat + "</p>";
                document.getElementById('longitude').innerHTML = "<p>Longitude : " + lng + "</p>";
            });       
            circle.bindTo('center', marker, 'position');
        } else {
            alert("The distance should be less than 1000m");
        }
    }
    function initDrag(e) {
        var l = function (a) {
            var b = {};
            if (a && a.touches && a.touches.length) {
                b.x = a.touches[0].clientX;
                b.y = a.touches[0].clientY
            }
            else {
                if (!a) var a = window.event;
                b.x = a.clientX;
                b.y = a.clientY
            }
            return b
        };
        var m = function (r) {
            if (obj && obj.className == "drag") {
                var n = l(r), s = n.x - o.x, t = n.y - o.y; obj.style.left = (obj.x + s) + "px";
                obj.style.top = (obj.y + t) + "px";
                obj.onmouseup = obj.ontouchend = function () {
                    var a = map.getDiv(), b = a.offsetLeft, c = a.offsetTop, f = a.offsetWidth, d = a.offsetHeight;
                    var h = drag_area.offsetLeft, i = drag_area.offsetTop, g = obj.offsetWidth, p = obj.offsetHeight;
                    var j = obj.offsetLeft + h + g / 2;
                    var k = obj.offsetTop + i + p / 2;
                    if (j > b && j < (b + f) && k > c && k < (c + d)) {
                        var u = 1;
                        var v = google.maps;
                        var w = new v.Point(j - b - u, k - c + (p / 2));
                        var x = dummy.getProjection();
                        var y = x.fromContainerPixelToLatLng(w);
                        var q = obj.style.backgroundImage.slice(4, -1).replace(/"/g, "");
                        createDraggedMarker(y, q); fillMarker(q);
                        checkInputMarker = 1;

                    }
                }
            } return false
        };
        if (!e) var e = window.event;
        obj = e.target ? e.target : e.srcElement ? e.srcElement : e.touches ? e.touches[0].target : null; if (obj.className != "drag") {
            if (e.cancelable) e.preventDefault();
            obj = null;
            return
        }
        else {
            z_index += 1; obj.style.zIndex = z_index.toString();
            obj.x = obj.offsetLeft;
            obj.y = obj.offsetTop;
            var o = l(e);
            if (e.type === "touchstart") {
                obj.onmousedown = null;
                obj.ontouchmove = m;
                obj.ontouchend = function () {
                    obj.ontouchmove = null;
                    obj.ontouchend = null;
                    obj.ontouchstart = initDrag
                }
            }
            else {
                document.onmousemove = m;
                document.onmouseup = function () {
                    document.onmousemove = null;
                    document.onmouseup = null;
                    if (obj) obj = null
                }
            }
        }
        return false
    }
    
    function updateGeofence() {
        if (parseFloat(document.getElementById("tbFenceDistance").value) <= 1000 && lat != "") {
    	var permanent = "Permanent";
    	var temporary = "Temporary";
    	
    	if(document.getElementById("cbPermanentFence").checked == true){
    		document.location.href='/geofence?distance=' + document.getElementById("tbFenceDistance").value + '&latitude=' + lat + '&longitude=' + lng + '&fenceType=' + permanent + '&name=' + document.getElementById("tbGeofenceName").value;
    	}
    	if(document.getElementById("cbTemporaryFence").checked == true){
    		document.location.href='/geofence?distance=' + document.getElementById("tbFenceDistance").value + '&latitude=' + lat + '&longitude=' + lng + '&fenceType=' + temporary + '&name=' + document.getElementById("tbGeofenceName").value;
    	}  
        }
        else{
        	alert("Please drag the marker and place it on the map.");
        }
    }
    
    function clearGeofence() {
    	var permanent = "Permanent";
    	var temporary = "Temporary";
    	
    	if(document.getElementById("cbClearPermanentFence").checked == true){
    		document.location.href='/deleteOutsidegeofence?fenceType=' + permanent;
    	}
    	if(document.getElementById("cbClearTemporaryFence").checked == true){
    		document.location.href='/deleteOutsidegeofence?fenceType=' + temporary;
    	} 
    }
    
    function clearAlerts(){
    	document.location.href='/deleteOutsidegeofence?fenceType=ClearAlert';
    }
    
    //clear overlay
    
    function clearOverlaysHist() {
    	  if (markerHist) {
    	    for (i in markerHist) {
    	    	markerHist[i].setMap(null);
    	    }
    	  }
    	}
    
    function checkGeofence(){
    	var hlbl = 0;

    	geocoder = new google.maps.Geocoder();

            //get json starts here
            $.getJSON('./getgeofence?fenceType=Permanent', function (data) {
                $.each(data.aaData, function (i, id) {
                    //adding markers start here
                    
                    geofencelat = id.latitude;
                    geofencelng = id.longitude;
                    geofenceDistance = id.distance;                    
                    
                });

            });
            
            $.getJSON('./data?type=10', function (data) {
                datalat = [];
                datalng = [];
                dataDate = [];
                $.each(data.aaData, function (i, id) {
                    //adding markers start here
                    
                    var lat = id.lat;
                    var lng = id.lng;
                    var datetime = id.dateTime;        
                    
                    datalat.push(lat);
                    datalng.push(lng);
                    dataDate.push(datetime);
                    
                });

            });
            //get json ends here 
            var latLng = new google.maps.LatLng(1.3667, 103.80);
            var options = {
                'zoom': 12,
                'center': latLng,
                'mapTypeId': google.maps.MapTypeId.ROADMAP
            };
            //map = new google.maps.Map(document.getElementById('map'), options);
            // Create a draggable marker which will later on be binded to a          
            // Circle overlay.          
            var marker = new google.maps.Marker({
                draggable: true,
                position: new google.maps.LatLng(geofencelat, geofencelng),
                title: 'Drag me!'
            });
            // Add a Circle overlay to the map.          
            var circle = new google.maps.Circle({
                radius: parseFloat(geofenceDistance), // 3000 km
                fillOpacity: 0.25
            });
            circle.bindTo('center', marker, 'position');
            
            movedOutGeofenceCount = 0;
            var htmlString = "<table width = '550'><tr><td colspan='4'><b>Outside Geofence Details (Last 10 Location)</b></td></tr><tr><td>&nbsp;</td></tr><tr><td>No.</td><td>Date & Time</td><td>Latitude</td><td>Longitude</td></tr>";
            for(var i = datalat.length -1; i > -1; i--){
                var dragable_marker = new google.maps.Marker({
                    position: new google.maps.LatLng(datalat[i],datalng[i])
                });
            	if(circle.getBounds().contains(dragable_marker.getPosition()) == true){
            		//alert("In the geofence");
            	}
            	else{
            		var no = movedOutGeofenceCount + 1;
            		htmlString = htmlString + "<tr><td>" + no + "</td><td>" + dataDate[i] + "</td><td>" + datalat[i] + "</td><td>" + datalng[i] + "</td></tr>";
            		movedOutGeofenceCount++;
            	}
            		
            }
            htmlString = htmlString + "</table></br></br>";
            $("#GeofenceDetails").html(htmlString);
            alert("Number of times that moved out of Geofence : " + movedOutGeofenceCount);
    	
    }
    
    
</script>

 <script>
 
function clearTempGeo() {
	  if (markerTemp) {
	    for (i in markerTemp) {
	    	markerTemp[i].setMap(null);
	    }
	  }
	}
</script>

 <script>
 
function clearPermGeo() {
	  if (markerPerm) {
	    for (i in markerPerm) {
	    	markerPerm[i].setMap(null);
	    }
	  }
	}
</script>


<!--  <script type="text/javascript" src="jquery.nivo.slider.js"></script>
    <script type="text/javascript">
        $(window).load(function () {
            $('#slider').nivoSlider();
        });

    </script> -->
    
</head>
<body onload="initialize();">
<div id="wrapper">
	<div id="header-wrapper">
		<div id="header" style="backgound-color:#0078D1;">
			<div id="logo">
				<h1><a href="#">OmniTrack</a></h1>
				 <!-- <p>Pte Ltd</p> -->
			</div>
			<div id="menu">
				<ul id="mapnav">
					<li><a href="index.html" accesskey="1" title=""><img src="images/EarthIcon.png" width="20" height="20"/> Map</a></li>
				<!-- 	<li><a href="facility.html" accesskey="1" title=""><img src="images/facility.png" width="20" height="20"/> Facility</a></li> -->
					<li><a href="Login.html" accesskey="1" title="">Logout</a></li>
				</ul>
			</div>
		</div>
	</div>

	<!-- <div id="banner"></div>-->
	<div id="page-wrapper">
		<div id="page">
			<div id="content">
				<div>
				<table>
				<tr>
				<td><h3 class="style3">Welcome To OmniTrack</h3></td>
				<td><div id = "imgNoAlert" class="rNoAlert">&nbsp;</div></td>
				</tr>
				</table>
					
				<div id="frontlayer" style="FILTER: alpha(opacity=10);opacity:0.95;"><br/><br/>
				

</div>

					<div id="map" class="gmap3"></div>
					
				</div>
			</div>
			<div id="sidebar">
				<h2>Information Window</h2>

				<div id="InformationBar" class="rpanel">
				<div id="Location"><h3 class="style2" style="color: #FFFFFF; "><img src="images/LocationIcon.png" width="30" height="30" />  Location</h3></div>
				<div id="info"><div id ='info'><p>Address :<br/><span class='title'>" + results[1].formatted_address +"</span></p><p>Date & Time :<br/><span class='title'>"+ id.dateTime+"</span></p>
				
				<p><input type='checkbox' id='His' onchange='showHistory()' value='Show History' />Show History</p>
				  <p>
				    <input type='checkbox' id="cbshowPermFence" value='cbshowPermFence' onchange='showPermanentGeofence()'/>Show Permanent GeoFence</p>
				      <p>
				    <input type='checkbox' id="cbshowTempFence" value='cbshowTempFence' onchange='showTemporaryGeofence()'/>Show Temporary GeoFence</p>
				  <p>&nbsp;</p>


				</div></div>
					<div id="Geofence"><h3 class="style2" style="color: #FFFFFF; "><img src="images/geofence_icon.png" width="30" height="30" />  Geofence</h3></div>
					
					<div id="GeofencePanel" style="color: #000000" class="style6">
						
						<p>Name : <input name="tbGeofenceName" id ="tbGeofenceName" type="text" value="Geofence 1" size="15" maxlength="12"/></p>
						
						<p>Radius Distance : <input name="tbFenceDistance" id ="tbFenceDistance" type="text" value="1000" size="7"/> M</p>
						
						<b>Input Coordinate</b>
						
						<p>Place the marker on the map to set the input coordinate.</p>

			            <p><input type="checkbox" name="cbPermanentFence" id="cbPermanentFence" value="Permanent GeoFence" checked="true" onchange="PermanentGeofence()" />Permanent&nbsp;<input type="checkbox" name="cbTemporaryFence" id="cbTemporaryFence" value="Temporary GeoFence" onchange="TemporaryGeofence()" />Temporary</p><div 
                            id="markers" class="style7"><div id="m1" class="drag" style="left: 0; background-image: url('http://maps.gstatic.com/mapfiles/ms/icons/ltblue-dot.png')"></div></div><div id="latitude"></div><div id="longitude"></div>
						<p>&nbsp;</p>
						<img id="CreateImg" alt="Create the geofence" src="images/Create.png" height="26" width="66" onclick="updateGeofence()" />
			        	<!--<input type="submit" name="btnCheckGeofence" id="btnCheckGeofence" value="Check Permanent Geofence" onclick="checkGeofence()"/> -->
			        	
			        	</div>
			        	<div id = "ClearGeofence"><h3 class="style4" style="color: #FFFFFF; ">  Clear Geofence</h3></div>
			        	<div id = "ClearGeofencePanel" style="color: #000000"><p>Please select the type of geofence that you would like to clear.</p></p><p><input type="checkbox" name="cbClearPermanentFence" id="cbClearPermanentFence" value="Clear Permanent GeoFence" checked="true" onchange="ClearPermanentGeofence()" />Permanent&nbsp;&nbsp;<input type="checkbox" name="cbClearTemporaryFence" id="cbClearTemporaryFence" value="Clear Temporary GeoFence" onchange="ClearTemporaryGeofence()" />Temporary</p><p>&nbsp;</p><p><img id="ClearImg" alt="Clear the geofence" src="images/ClearButton.png" height="26" width="66" onClick="clearGeofence()"/></p></div>
			        	
			        	</div>

			</div>
		</div>
	</div>
</div>

	<div id="GeofenceDetails"  class="style1">


</div>
	</div>
	<!-- <div id="footer-wrapper">
		<div id="footer-content" align="center" style="padding:35px 0px 0px 0px;">
			<div class="slider-wrapper theme-default" style="width:800px; height:260px;" >
            <div id="slider" class="nivoSlider">
                <img src="images/header.jpg" data-thumb="images/header.jpg" alt="" />
                <img src="images/1.jpg" data-thumb="images/1.jpg" alt=""/>
                <img src="images/2.jpg" data-thumb="images/2.jpg" alt="" data-transition="slideInLeft" />
                <img src="images/3.jpg" data-thumb="images/3.jpg" alt=""  />
				 <img src="images/4.jpg" data-thumb="images/4.jpg" alt="" />
				  <img src="images/5.jpg" data-thumb="images/5.jpg" alt=""  />
            </div>
        </div>

	</div>
</div> -->
<div id="footer">
	<p>Copyright (c) by Nanyang Polytechnic.</p>
</div>
</body>
</html>
